package com.saltedfish.tool.ui.calendar

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import cn.droidlover.xdroidmvp.event.BusProvider
import cn.droidlover.xdroidmvp.log.XLog
import cn.droidlover.xdroidmvp.mvp.XFragment
import com.saltedfish.tool.R
import com.saltedfish.tool.dao.*
import com.saltedfish.tool.dialog.UIFlagDoneDialog
import com.saltedfish.tool.dialog.UIUpdateTimeDialog
import com.saltedfish.tool.model.CalenderInfo
import com.saltedfish.tool.model.DayTable
import com.saltedfish.tool.model.ModelInfo
import com.saltedfish.tool.present.XFP
import com.saltedfish.tool.ui.calendar.CalendarAdapter.CalendarListener
import com.saltedfish.tool.util.CalendarReminderUtils
import com.saltedfish.tool.util.DateUtils
import com.saltedfish.tool.util.SharePreferceUtils
import com.saltedfish.tool.util.ViewClickUtils
import kotlinx.android.synthetic.main.fragment_today.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList


class FragmentToday : XFragment<XFP>(), View.OnClickListener {

    companion object {
        fun newInstance(): FragmentToday {
            return FragmentToday()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_today
    }

    override fun initData(savedInstanceState: Bundle?) {
        var database = AppDataUtils.initRoom(context)
        dayDBDao = database.dayDBDao()
        subFlagModelDao = database.subFlagDao()
        flagModelDao = database.flagInfoDao()
        calendarDao = database.calenderDao()
    }

    override fun loadData() {
        super.loadData()
        showTopData()
       // initDataShow()
    }

    //显示顶部数据资源
    private fun showTopData() {
        ViewClickUtils.setViewClick(this, tips_rc_xgdtsj)
        ViewClickUtils.setViewClick(this, tips_rc_bk)
    }

    override fun newP(): XFP? {
        return null
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tips_rc_xgdtsj -> {
                tips_rc_xgdtsj.visibility = View.GONE
                SharePreferceUtils.setString("tips_rc_xgdtsj", "tips_rc_xgdtsj")
            }
            R.id.tips_rc_bk -> {
                tips_rc_bk.visibility = View.GONE
                SharePreferceUtils.setString("tips_rc_xgdtsj", "tips_rc_xgdtsj")
            }
        }
    }


    var cal: Calendar? = null
    private var dayLists: MutableList<DayTable> = ArrayList()
    var dayDBDao: DayDBDao? = null
    var calendarDao: CalenderDao? = null

    var subFlagModelDao: SubFlagModelDao? = null
    var flagModelDao: FlagInfoDao? = null

    private var linearLayoutManager: LinearLayoutManager? = null
    private var adapter: CalendarAdapter? = null

    private var today: String? = null
    val sdf = SimpleDateFormat("yyyy-MM-dd")
    val sdfs = SimpleDateFormat("yyyy/MM/dd")

    override fun onResume() {
        super.onResume()

        cal = Calendar.getInstance()
        cal!!.time =  Date()
        today = sdf.format(cal!!.time)


        updateCalendar()

    }



    //刷新列表
    private fun updateCalendar() {
        dayLists.clear()
        dayLists =  dayDBDao!!.getByDay(today)

        if(dayLists.size !=0){
            linear_today_rest.visibility = View.GONE
            var tipRC =  SharePreferceUtils.getString("tips_rc_xgdtsj")
            if(TextUtils.isEmpty(tipRC)){
                tips_rc_xgdtsj.visibility = View.VISIBLE
                tips_rc_bk.visibility = View.VISIBLE
            }
            linearLayoutManager = LinearLayoutManager(context)
            mRecyclerView.layoutManager = linearLayoutManager
            adapter = CalendarAdapter(dayLists)
            mRecyclerView.adapter = adapter

            adapter!!.setCalendarListener(object : CalendarListener {
                override fun selectCalendar(item: DayTable) {
                    dayDBDao!!.update(item)
                    var subFlagModels = subFlagModelDao!!.getBySubId(item.subId)
                    val modelInfo = ModelInfo()
                    modelInfo.updateFlag = true

                    if (item.isTick) {
                        modelInfo.updateCalendar = true
                        subFlagModels.tickNum = subFlagModels.tickNum + 1
                    } else {
                        modelInfo.updateCalendar = false
                        subFlagModels.tickNum = subFlagModels.tickNum - 1
                    }
                    subFlagModels.progress = subFlagModels.tickNum.toFloat() / subFlagModels.tick.toFloat()
                    var flagInfo = flagModelDao!!.getById(subFlagModels.fId)
                    flagInfo.completeDay = sdfs.format(cal!!.time)
                    subFlagModels.completeDay = sdfs.format(cal!!.time)

//                    XLog.e("-flagInfo.completeDay--->${subFlagModels}>")
                    if (subFlagModels.progress == 1.0f && subFlagModels.status == "已延期") {
                        //子目标打卡完成后，删除可能延期重复出现的打卡
                        dayDBDao!!.deleteAllBySubIdOrDay(subFlagModels.subId, today)
                    }
                    //更新子目标
                    subFlagModelDao!!.update(subFlagModels)

                    var flagLists = subFlagModelDao!!.getAllByFlagId(subFlagModels.fId)

                    var flagProgressList = subFlagModelDao!!.getAllByFlagIdAndProgress(subFlagModels.fId, 1.0f, "提前完成")

                    if (flagLists.size == flagProgressList.size) {
                        flagInfo.isComplete = true
                        initFlagDoneDialog(1, flagInfo.title)
                    } else {
                        flagInfo.isComplete = false
                        if (subFlagModels.progress == 1.0f) {
                            initFlagDoneDialog(0, item.title)
                        }
                    }
                    //更新
                    flagModelDao!!.update(flagInfo)

                    BusProvider.getBus().post(modelInfo)
                    //更新列表
                    updateCalendar()

                }

                override fun selectCalendarDate(item: DayTable) {
                    initUpdateTime(item)
                }
            })

        }else{
            linear_today_rest.visibility  = View.VISIBLE
        }
    }


    private var uiFlagDoneDialog: UIFlagDoneDialog? = null

    /**
     *  打卡完成弹窗
     */
    private fun initFlagDoneDialog(type: Int, title: String) {
        if (uiFlagDoneDialog == null) {
            uiFlagDoneDialog = UIFlagDoneDialog(context)
        }
        uiFlagDoneDialog!!.updateFlagDone(type, title);
        uiFlagDoneDialog!!.show()
    }

    private var weekDialog: UIUpdateTimeDialog? = null

    /**
     * 重复时间选择（星期和每天的时间节点）
     */
    private fun initUpdateTime(item: DayTable) {
        if (weekDialog == null) {
            weekDialog = UIUpdateTimeDialog(context)


        }
        weekDialog!!.setListener(object : UIUpdateTimeDialog.SimpleDateListener() {
            override fun onDateClicks(repeatTime: String) {
//                XLog.e("--subFlagModel--->>$repeatTime")
                item.repeatTime = repeatTime
                dayDBDao!!.update(item)

                var calendarInfo = calendarDao!!.getById(item.subId)
                if (calendarInfo != null) {
                    calendarDao!!.deleteAllCalenderBySubId(item.subId)
                    CalendarReminderUtils.deleteCalendarEvent(context, calendarInfo.eventId)
                }

                var subFlagModels = subFlagModelDao!!.getBySubId(item.subId)
                if (subFlagModels.isRemind) {
                    var endTime = subFlagModels.endTime
                    var repeatTimes = subFlagModels.repeatTime

                    //比例两个时间天数时间的大小
                    var index = DateUtils.compareEqualsDate(today, endTime)
                    if (index == 1) {
                        subFlagModels.startTime = DateUtils.getNextDay(today, 1)
                        subFlagModels.endTime = endTime
                        subFlagModels.repeatTime = repeatTimes
                        CalendarReminderUtils.updateCalendarEvent(context, subFlagModels)
                    }

                    //比例两个当前时间的大小
                    val repeatTime2: Array<String> = repeatTime.split("-").toTypedArray()
                    var hours = DateUtils.compareEqualsHour(repeatTime2[1], "")
                    if (hours == 0) {
                        subFlagModels.endTime = today
                        subFlagModels.startTime = today
                        subFlagModels.repeatTime = repeatTime
                        var subId = subFlagModels.subId
                        val random = (Math.random() * 100).toInt()
                        subFlagModels.subId = subId + random
                        var eventId = CalendarReminderUtils.addCalendarEvent(context, subFlagModels)
//                    XLog.e("-----eventId-----" + eventId)

                        var calendarInfo = CalenderInfo()
                        calendarInfo.eventId = eventId
                        calendarInfo.subId = subId
//                        calendarInfo.repeatTime = repeatTime
                        calendarInfo.startTime = subFlagModels.startTime
                        calendarDao!!.insert(calendarInfo)
//                    XLog.e("-----calendarDao-----"+calendarDao!!.all)

                    }
                }
                updateCalendar()

            }
        })

        weekDialog!!.updateDate(item.repeatTime)
        weekDialog!!.show()
    }


}